from app.extensions import SessionLocal
from app.models.Clas import Clas
from app.repositories.ClasRepo import ClasRepository
from app.asserts import Codes
from fastapi import APIRouter, Response, status
class ClasService():
    def __init__(self, db: SessionLocal):
        # 创建DAO层对象
        self.repo = ClasRepository(db)

    def add_clas(self, clas_name):
        #判断班级是否已经存在
        clas = self.repo.get_clas_by_name(clas_name)
        if clas is not None:
            return {"code": status.HTTP_409_CONFLICT, "data": None, "message": "班级已经存在"}
        #添加班级
        result = self.repo.add_clas(clas_name)
        if result:
            return {"code": status.HTTP_200_OK, "data": None, "message": "班级已创建成功"}
        return {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "data": None, "message": "班级创建失败"}
    def get_by_keyword(self, keyword):
        """
        根据关键字查询数据
        :param keyword: 关键字
        :return:
        """
        data = self.repo.get_by_keyword(keyword)
        return {"code": status.HTTP_200_OK, "data": data, "message": "查询成功"}

    def modify_clas(self, id, new_name):
        # 检查新名称是否已存在
        if self.repo.get_clas_by_name(new_name):
            return {"code": status.HTTP_409_CONFLICT,"data": None,"message": f"班级名称已存在: {new_name}"}
        # 执行更新操作
        success = self.repo.modify_clas(id, new_name)
        if success:
            return {"code": status.HTTP_200_OK,"data": None,"message": "修改成功"}
        else:
            return {"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"data": None,"message": "修改失败"}

    def delete_clas(self, id):
        if not self.repo.get_clas_by_id(id):
            return {"code": status.HTTP_404_NOT_FOUND, "data": None, "message": "班级不存在" }
        success = self.repo.delete_clas(int(id))
        if success:
            return {"code": status.HTTP_200_OK, "data": None, "message": "删除成功"}
        else:
            return {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "data": None, "message": "修删除失败"}